<{include file="public/header.html"}>

<style type="text/css">
    .btn_expmenu {background-image:url('<{$VIRT_IMAGES}>/btn/list-items.gif') !important;}
    .btn_exphtml {background-image:url('<{$VIRT_IMAGES}>/btn/f_html.png') !important;}
    .btn_exppdf  {background-image:url('<{$VIRT_IMAGES}>/btn/f_pdf.png') !important;}
    .btn_expxls  {background-image:url('<{$VIRT_IMAGES}>/btn/f_excel.png') !important;}
</style>

<script language="javascript">
<!--
if (Ext.form.ComboBox) {
    Ext.apply(Ext.form.ComboBox.prototype, {
        triggerAction:'all',
        selectOnFocus:true,
        editable:false,
        mode:'local',
        lazyInit:false,
        emptyText:'',
        displayField:'sText',
        anchor:"95%"
    });
}
if (Ext.form.TimeField) {
    Ext.apply(Ext.form.TimeField.prototype, {
        format:'H:i',
        emptyText:'',
        increment:10,
        maxLength:5,
        anchor:"",
        width:80
   });
}

//project grid list
var jstore = new Ext.data.JsonStore({
    url : './projectAjax.php',
    baseParams : {strAction:'projectlist',chkCreate:'0',chkManage:'0',chkDo:'0'},
   	root: "data",
	totalProperty:"total",
	fields: ['sID','pCode','pName','pType','sPri','isPer','sDate','fDate','sMan','cUser','cDate'] 
});
jstore.on('beforeload',function(jst,option) {
    var c1 = (Ext.getCmp("chkMyCreate").checked ? 1 : 0);
    var c2 = (Ext.getCmp("chkMyManage").checked ? 1 : 0);
    var c3 = (Ext.getCmp("chkMyDo").checked ? 1 : 0);
    if (c1==0 && c2==0 && c3==0) {
        Ext.Msg.alert('错误',"请至少选择一个项目过滤条件!");
        return false;
    } else {
        jst.removeAll(); //clear gird data
        jst.baseParams["chkCreate"] = c1;
        jst.baseParams["chkManage"] = c2;
        jst.baseParams["chkDo"] = c3;
        return true;
    }
});

var rowNumb = new Ext.grid.RowNumberer();
var selMode = new Ext.grid.CheckboxSelectionModel({singleSelect:true});  // add checkbox column
var colMode = new Ext.grid.ColumnModel([rowNumb,selMode,
    {header:"!",dataIndex:'sPri',width:25,align:"center",hideable:false,
        tooltip:"优先级",renderer:function(value) {
            if (value=="1") return "<font color='red'>高</font>";
            else if (value=="3") return "<font color='green'>低</font>";
            else return "中";
        }},
    {header:"项目名称",dataIndex: 'pName',css:GRID_LINK_CSS,width: 240,hideable:false},
    {header:"项目编号",dataIndex:'pCode',width:100,hideable:false},
    {header:"项目类型",dataIndex:'pType',width:100},
    {header:"开始日期",dataIndex:'sDate',width:90,align:'center'},
    {header:"结束日期",dataIndex:'fDate',width:90,align:'center'},
    {header:"开放范围",dataIndex:'isPer',width:80},
    {header:"项目负责人",dataIndex:'sMan',width:100,hideable:false},
    {header:"项目创建人",dataIndex:'cUser',width:100,hideable:false},
    {header:"创建时间",dataIndex:'cDate',width:140,align:'center'}
]);
colMode.defaultSortable = true;

var expMenu = new Ext.menu.Menu({
	id:'exportMenu',
	items:[
		{id:'htmlExp',text:"HTML导出",tooltip:'将项目导出保存成HTML文件',iconCls:'btn_exphtml'},
		{id:'pdfExp',text:"PDF导出",tooltip:'将项目导出保存成PDF文件',iconCls:'btn_exppdf'},
		{id:'xlsExp',text:"Excel导出",tooltip:'将项目导出保存成EXCEL文件',iconCls:'btn_expxls'}]
});

var filterBar = new Ext.Toolbar({
    id:'idFilter',
    items: ["项目过滤:&nbsp; ",{id:"chkMyCreate",xtype:'checkbox',value:'1',checked:true, boxLabel:'我创建 &nbsp; '},
            {id:"chkMyManage",xtype:'checkbox',value:'1',checked:true, boxLabel:'我负责 &nbsp; '},
            {id:"chkMyDo",xtype:'checkbox',value:'1', boxLabel:'我参与 &nbsp; '},
            {id:"btnQuery",text:'查询',tooltip:'查询项目信息',iconCls:'btn_query',handler:loadProjList},
            ' &nbsp; &nbsp; &nbsp; ','-', {
                id:'btnAdd',text:'新增',tooltip:'新建一个项目',iconCls:'btn_add',
                handler:function() {
                    winProject.show();
                    projForm.form.reset();
                    setWorkDay('<{$aDefaultWeek}>');
                }
            }, {id:"btnDelete",text:'删除',tooltip:'删除当前选择的项目',iconCls:'btn_remove',
                handler:function() {
                    var records = gridTask.selModel.getSelections(); //得到被选择的行的数组
                    if (records.length == 0){ 
                        Ext.Msg.alert("提示信息","请先选择一个项目！");
                    } else if (records[0].get("cUser")!= "<{$sCreateUser}>" && records[0].get("sMan")!= "<{$sCreateUser}>") {
                    	Ext.Msg.alert("错误","您不是这个项目的创建者或负责人，无权删除本项目！");
                    	Ext.getCmp("btnDelete").setDisabled(true);
                    } else {
                        doDelTask(records[0].get("sID"));
                    }
                }
            },'-',{text:'项目导出',iconCls:'btn_expmenu',menu:expMenu}
            ] //end toolbar item
});

var gridTask = new Ext.grid.GridPanel({
    layout:'form',border:false,
    region:'center',
    store:jstore,
    cm:colMode,
    sm:selMode,
    trackMouseOver:true,
    loadMask:true,
    viewConfig:{autoFill:true,forceFit:true},
    tbar:filterBar,
    bbar: new Ext.PagingToolbar({
        pageSize:20,store:jstore,
        displayMsg:'第{0} 到 {1} 条数据 共{2}条',
        emptyMsg:'没有数据',displayInfo:true })

    <{* listeners:{'render':function(){ pageBar.render(this.tbar); }} //实现多行 toolbar工具栏 *}>
});
gridTask.on("cellclick",function(grid,rowIndex,colIndex,eObj) {
	var record = grid.getStore().getAt(rowIndex);  // Get the Record
   	Ext.getCmp("btnDelete").setDisabled((record.get("cUser")!="<{$sCreateUser}>" && record.get("sMan")!="<{$sCreateUser}>"));

    if (rowIndex >= 0 && colIndex==3) {
        grid.fireEvent("rowdblclick",grid,rowIndex,colIndex,eObj);
    }
});
gridTask.on("rowdblclick",function(grid,rowIndex,eObj) {
    if (rowIndex >= 0) {
        var record = grid.getStore().getAt(rowIndex);  // Get the Record
        winProject.show();
        projForm.form.reset();
        loadProject(record.get("sID"));
    }
});

var viewport = new Ext.Viewport({
    layout: 'border',
    items : gridTask
});

function checkManage(comb,record,index) {
    if (record.get("sValue") == '3') {
    	Ext.getCmp("sManager").setValue("<{ $sDefaultManager }>");
        Ext.getCmp("sManager").disable();
    } else {
        Ext.getCmp("sManager").enable();
    }
}

var projForm = new Ext.FormPanel({
    labelWidth:85,
    labelAlign:'right',
    frame:true,
    layout:'form',
    region:'center',
    reader:Ext.data.JsonReader({
        successProperty:"success",
        totalProperty:"total", 
        id: "strProjectID" 
        }, ['strProjectName','strProjectCode','strStartDate','strPriority',
            'strProjectType','strFinishDate','strManager','strContent','strWorkDay',
            'strWorkTime','strAMStartTime','strPMStartTime','strIsPersonal','strAMEndTime',
            'strPMEndTime','strCreateUser','strCreateDate'] 
        ),

    items: [{xtype:"hidden",name:"strProjectID",id:'sProjectID',value:''},
       {xtype:'textfield',fieldLabel:'项目名称',name:'strProjectName',anchor:'96%',vtype:'dblCharField',
        maxLength:250,allowBlank:false
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:0.5,
            layout:'form',
            items :[{xtype:"textfield", fieldLabel:"项目编号", name:"strProjectCode", 
                     maxLength:50,anchor:'96%'},
                    {xtype:"datefield",fieldLabel:'项目开始日期',name:'strStartDate',id:'sStartDate'},
                    {xtype:"combo",hiddenName:"strIsPersonal",fieldLabel:"项目开放范围",forceSelection:true,
                        valueField:'sValue',value:'<{ $sSECURITY }>',
                        listeners:{'select':checkManage},
                        store:new Ext.data.SimpleStore({
                            data  :<{ $aSECURITY }>,
                            fields:['sValue','sText']
                        }) } ]
        },{
            columnWidth:0.5,
            layout:'form',
            items:[{xtype:"textfield",name:"strProjectType",fieldLabel:"项目类别",
                maxLength:30,anchor:'96%'},
                {xtype:"datefield",fieldLabel:'项目结束日期',name:'strFinishDate',id:'sFinishDate'},
                {xtype:"combo",hiddenName:"strManager",id:"sManager",fieldLabel:"项目负责人",
                valueField:'sValue',value:'<{ $sDefaultManager }>',
                store:new Ext.data.SimpleStore({
                    data  :<{ $aManager }>,
                    fields:['sValue','sText']
                }) }]
        }]
    },{
        xtype:'htmleditor',name:'strContent',fieldLabel:'项目情况说明',
        height:150,width:540 //anchor:'98%'
    },{
        xtype:"panel",
        layout:"column",
        isFormField:true,
        fieldLabel:"工作日",
        items:[{xtype:"hidden",name:"strWorkDay",id:'sWorkDay',value:''},
          {
            columnWidth:0.14,
            layout:'form',items:[{hideLabel:true,
            xtype:'checkbox',boxLabel:'星期日',name:"strWeek0",id:"sWeek0"}]
        },{
            columnWidth:0.14,
            layout:'form',items:[{hideLabel:true,
            xtype:'checkbox',boxLabel:'星期一',name:"strWeek1",id:"sWeek1"}]
        },{
            columnWidth:0.14,
            layout:'form',items:[{hideLabel:true,
            xtype:'checkbox',boxLabel:'星期二',name:"strWeek2",id:"sWeek2"}]
        },{
            columnWidth:0.14,
            layout:'form',items:[{hideLabel:true,
            xtype:'checkbox',boxLabel:'星期三',name:"strWeek3",id:"sWeek3"}]
        },{
            columnWidth:0.14,
            layout:'form',items:[{hideLabel:true,
            xtype:'checkbox',boxLabel:'星期四',name:"strWeek4",id:"sWeek4"}]
        },{
            columnWidth:0.14,
            layout:'form',items:[{hideLabel:true,
            xtype:'checkbox',boxLabel:'星期五',name:"strWeek5",id:"sWeek5"}]
        },{
            columnWidth:0.14,
            layout:'form',items:[{hideLabel:true,
            xtype:'checkbox',boxLabel:'星期六',name:"strWeek6",id:"sWeek6"}]
        }]
    },{
        xtype:"panel",
        layout:"column",
        anchor:'100%',
        items:[{
            columnWidth:0.5,
            layout:'form',
            items :[{xtype:"timefield",fieldLabel:'上午上班时间',name:'strAMStartTime',id:'sAMStartTime',
                value:'<{ $aDefaultTime.AM_START_TIME }>',listeners:{'select':calcDayTime}},
                {xtype:"timefield",fieldLabel:'下午上班时间',name:'strPMStartTime',id:'sPMStartTime',
                value:'<{ $aDefaultTime.PM_START_TIME }>',listeners:{'select':calcDayTime}},
                {xtype:"textfield",fieldLabel:"每日工作时间",name:"strWorkTime",
                    id:"sWorkTime",readOnly:true,anchor:'96%',value:"8 小时"},
                {xtype:"textfield",fieldLabel:"项目创建人",name:"strCreateUser",
                    readOnly:true,anchor:'96%'}]
        },{
            columnWidth:0.5,
            layout:'form',
            items :[{xtype:"timefield",fieldLabel:'上午下班时间',name:'strAMEndTime',id:'sAMEndTime',
                    value:'<{ $aDefaultTime.AM_END_TIME }>',listeners:{'select':calcDayTime}},
                {xtype:"timefield",fieldLabel:'下午下班时间',name:'strPMEndTime',id:'sPMEndTime',
                    value:'<{ $aDefaultTime.PM_END_TIME }>',listeners:{'select':calcDayTime}},
                {xtype:"combo",hiddenName:"strPriority",fieldLabel:"优先级",forceSelection:true,
                    value:'2',valueField:'sValue',
                    store:new Ext.data.SimpleStore({
                        data:<{ $aImportance }>,
                        fields:['sValue','sText']
                    })
                },
                {xtype:"textfield",fieldLabel:"创建时间",name:"strCreateDate",
                    readOnly:true,anchor:'96%'}]
        }]
    }],

    buttons: [{
            text:'保 存',id:'btnSave',handler:doSaveTask,tooltip:'保存当前项目信息' 
        },{
            text:'关 闭',id:'btnCanel',tooltip:'关闭当前窗口',
            handler:function() {winProject.hide();}
        }]
});
var winProject = new Ext.Window({
    title:'项目信息维护',
    width:700,height:500,collapsible:true, maximizable:false,
    layout:'fit',plain:true,bodyStyle:'padding:1px;',
    modal:true,closeAction:'hide',items:projForm
});

function getWorkDay(sWorkDay) {
    return (Ext.getCmp(sWorkDay).checked ? "1" : "0");
}
function setWorkDay(sWorkday) {
    for (var i=0; i<sWorkday.length; i++) {
        Ext.getCmp("sWeek"+i).setValue(sWorkday.charAt(i)=="1"?true:false);
    }
}
function loadProject(projectID) {
    projForm.getForm().load({
        url:'./projectAjax.php', 
        //waitMsg:'正在载入数据...', 
        params:{ strProjectID:projectID,strAction:ACTION_VIEW},

        success : function(form, action){
            Ext.getCmp("sProjectID").setValue(projectID);
            if (action.result.data.strWorkDay != "") {
                setWorkDay(action.result.data.strWorkDay);
            }
        },
        failure : function(form, action){
            Ext.Msg.alert('错误', '数据加载失败！');
        }
    });
}

//根据上午上班时间和下午下班时间，计算每日工时
function calcDayTime() {
    //判断时间是否合法的
    var a = Ext.getCmp("sAMStartTime").getValue();     //上午上班时间
    var b = Ext.getCmp("sAMEndTime").getValue();       //上午下班时间
    var c = Ext.getCmp("sPMStartTime").getValue();     //下午上班时间
    var d = Ext.getCmp("sPMEndTime").getValue();       //下午下班时间

    if (a > b) {
        Ext.Msg.alert("错误","上午下班时间比上午上班时间早，请修正");
        return false;
    }
    if (c > d) {
        Ext.Msg.alert("错误","下午下班时间比下午上班时间早，请修正");
        return false;
    }
    if (b > c) {
        Ext.Msg.alert("错误","下午上班时间比上午下班时间早，请修正");
        return false;
    }

	var ams1 = a.substr(0,2);
	var ams2 = a.substr(3,2);
	var amf1 = b.substr(0,2);
	var amf2 = b.substr(3,2);
	var pms1 = c.substr(0,2);
	var pms2 = c.substr(3,2);
	var pmf1 = d.substr(0,2);
	var pmf2 = d.substr(3,2);

	var amTotal = (amf1-ams1)*60 + (amf2 -ams2);    //上午间隔分钟
	var pmTotal = (pmf1-pms1)*60 + (pmf2 -pms2);    //下午间隔分钟
	var dayhour = (amTotal + pmTotal)/60;           //计算一天总的小时数
	Ext.getCmp("sWorkTime").setValue(Math.round(dayhour*100)/100 + " 小时"); 
}
function checkForm() {
    //校验项目开始和结束时间
    var sd = Ext.getCmp("sStartDate").getValue();
    var fd = Ext.getCmp("sFinishDate").getValue();
    if (sd > fd) {
        Ext.Msg.alert("错误","项目开始时间比项目结束时间还早，请修正");
        return false;
    }

    var sWorkday = getWorkDay("sWeek0")+
                   getWorkDay("sWeek1")+getWorkDay("sWeek2")+
                   getWorkDay("sWeek3")+getWorkDay("sWeek4")+
                   getWorkDay("sWeek5")+getWorkDay("sWeek6");
    if (sWorkday == "0000000") {
        Ext.Msg.alert("数据错误","必须至少选择一个工作日");
        return false;
    } else {
        Ext.getCmp("sWorkDay").setValue(sWorkday);
    }

    return true;
}
function doSaveTask() {
    var ff = projForm.getForm();
    if (ff.isValid()) {
        if (!checkForm()) return false;
        var sAction = (Ext.getCmp("sProjectID").getValue()=="" ? ACTION_INSERT : ACTION_UPDATE);
        ff.submit({
            url     : './projectAjax.php',
            method  : 'POST',
            //waitMsg : '正在保存数据...',
            params  : {strAction:sAction},
            success : function(form, action){
                Ext.Msg.alert('提示',action.result.msg,
                    function(){winProject.hide();jstore.reload();});
                },
            failure : function(form, action) {
                //Ext.Msg.alert('错误', action.response.responseText);
                Ext.Msg.alert('错误', '数据保存失败！');
            }
        });
    } else { //form checked is invalid
        Ext.Msg.alert('错误',"填写的数据有错误，请检查");
    }
};
function doDelTask(sProjectID) {
    if (sProjectID != "") {
        Ext.Msg.confirm('确认信息',"该项目下的所有相关信息将会被一起删除，是否继续？",function (btn) {
            if (btn == "yes") {
                Ext.Ajax.request({
                    url : './projectAjax.php',
                    params : {strAction:ACTION_DELETE,strProjectID:sProjectID},
                    success: function() {
                        Ext.Msg.alert('删除项目',"项目删除成功",
                        function(){winProject.hide();loadProjList();});},
                    failure: function(form,action) {
                        Ext.Msg.alert('删除项目',action.result.msg);
                    }
                });
            }
        });
    }
}
//init page
function loadProjList() {
    jstore.load({params:{start:0,limit:20}});
}
loadProjList();
//-->
</script>

<{include file="public/footer.html"}>